package io.github.leon406.capp.ui.other

import android.content.Intent
import androidx.recyclerview.widget.LinearLayoutManager
import io.github.leon406.capp.R
import io.github.leon406.capp.base.mvp.LCEMvpFragment
import io.github.leon406.capp.bean.MeiZi
import io.github.leon406.capp.bean.Result
import io.github.leon406.capp.extension.toast
import io.github.leon406.capp.ui.preview.PhotoPreviewActivity
import kotlinx.android.synthetic.main.fragment_other.*

class OtherFragment : LCEMvpFragment<OtherContract.View, OtherPresenter>(), OtherContract.View {

    var page: Int = 1
    var adapter: MeiziAdapter? = null
    override fun bindContent(): Int = R.layout.fragment_other
    override fun onContentViewInit() {
        showLoading()
        rv.layoutManager = LinearLayoutManager(activity!!)

        getPresenter().fetch(page++)
    }


    override fun bindPresenter() = OtherPresenter()

    override fun onFetch(meiZi: MeiZi) {
        showContent()
        if (adapter == null) {
            adapter = MeiziAdapter(meiZi.results as MutableList<Result>)
            adapter?.setOnLoadMoreListener {
                activity?.toast("loadMore")
                getPresenter().fetch(page++)
            }
            srl.setOnRefreshListener {
                getPresenter().fetch(page = 1)
                srl.isRefreshing = false
            }
            adapter?.setOnItemChildClickListener { adapter, view, position ->
                activity?.toast(" children click ${view.id == R.id.iv}")
                var intent = Intent(activity, PhotoPreviewActivity::class.java).apply {
                    putExtra("url", (adapter as MeiziAdapter).data[position].url)
                }
                activity!!.startActivity(intent)
            }
            rv.adapter = adapter
        } else {
            if (page == 1) {
                adapter?.setNewData(meiZi.results as MutableList<Result>)
            } else {
                adapter?.addData(meiZi.results as MutableList<Result>)
            }
        }

        srl.isRefreshing = false
        if (meiZi.results.size < 10) {
            adapter?.loadMoreEnd()
        } else {
            adapter?.loadMoreComplete()
        }

    }

    override fun onError(throwable: Throwable) {
        super.onError(throwable)
        showError()
        srl.isRefreshing = false
    }
}